import random


def get_random_color():
    return tuple([random.randint(0, 255) for i in range(3)])


def create_valid_code_img(request):

    # 方式1：通过静态资源文件加载
    # with open('.jpg','rb') as img:
    #     data = img.read()
    # return HttpResponse(data)

    # 方式2：通过pillow模块
    # from PIL import Image
    # img = Image.new('RGB', (270, 40), color=get_random_color())
    #
    # with open('validCode.png','wb') as f:
    #     img.save(f, 'png')
    # with open('validCode.png', 'rb') as f:
    #     validcode_img = f.read()
    # return HttpResponse(validcode_img)

    # 方式3：使用内存存储图片
    # from PIL import Image
    # from io import BytesIO
    #
    # img = Image.new('RGB', (270, 40), color=get_random_color())
    # f=BytesIO()
    # img.save(f, 'png')
    # data = f.getvalue()
    # return HttpResponse(data)

    # 方式4：
    from PIL import Image, ImageDraw, ImageFont
    from io import BytesIO

    img = Image.new('RGB', (270, 40), color=get_random_color())
    draw = ImageDraw.Draw(img)
    font1 = ImageFont.truetype('static/fonts/fzst.TTF', size=38)

    # 保存验证码字符串
    valid_code_str = ''
    for i in range(5):
        random_num = str(random.randint(0, 9))
        random_lower_alpha = chr(random.randint(97, 97 + 25))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_lower_alpha, random_upper_alpha])
        valid_code_str += random_char
        draw.text((i * 45 + 20, -5), random_char, get_random_color(), font=font1)

    request.session["valid_code_str"] = valid_code_str

    # 增加燥点 燥线
    width = 270
    height = 40
    for i in range(random.randint(3, 10)):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw.line((x1, y1, x2, y2), fill=get_random_color())

    for i in range(100):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())

    f = BytesIO()
    img.save(f, 'png')
    data = f.getvalue()
    return data